import logging
import os.path
import time


class infoFilter(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.INFO


class errFilter(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.ERROR

class logger:
    # 获取日志对象--定义类方法@classmethod
    @classmethod
    def getlog(cls):
        # 获取日志记录器对象,名称位为当前模块的名称
        cls.logger = logging.getLogger(__name__)

        # 设置日志记录器的级别
        cls.logger.setLevel(logging.DEBUG)

        # 设置日志保存路径
        LOG_PATH = "./logs/"
        # 同时还要判断是否存在这个路径,不存在则先创建
        if not os.path.exists(LOG_PATH):
            os.mkdir(LOG_PATH)

        # 将日志输出到日志文件中
        '''
        logs
            2025-10-09.log
            2025-10-09-info.log
            2025-10-09-err.log
        '''
        now = time.strftime("%Y-%m-%d")
        logo_name = LOG_PATH + now + ".log"
        info_logo_name = LOG_PATH + now + "-info.log"
        err_logo_name = LOG_PATH + now + "-err.log"

        # 创建文件处理器
        all_handler = logging.FileHandler(logo_name, encoding="utf-8")
        info_handler = logging.FileHandler(info_logo_name, encoding="utf-8")
        err_handler = logging.FileHandler(err_logo_name, encoding="utf-8")
        # 将日志打印在控制台,方便对每个接口日志错误信息进行排查
        stream_handler = logging.StreamHandler()

        # 设置日志格式
        formatter = logging.Formatter("%(asctime)s %(levelname)s [%(name)s (%(funcName)s:%(lineno)d)] - %(message)s")
        all_handler.setFormatter(formatter)
        info_handler.setFormatter(formatter)
        err_handler.setFormatter(formatter)
        stream_handler.setFormatter(formatter)

        # 添加过滤器
        info_handler.addFilter(infoFilter())
        err_handler.addFilter(errFilter())


        # 将文件处理器添加到日志记录器中
        cls.logger.addHandler(all_handler)
        cls.logger.addHandler(info_handler)
        cls.logger.addHandler(err_handler)
        # cls.logger.addHandler(stream_handler)

        return cls.logger
